package com.homework;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author 于振晗
 * @title: HomeWork02
 * @description: TODO 向第一题的xml添加一条数据
 * @date 2020年09月08日
 * @path com.homework
 */
public class HomeWork02 {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader saxReader = new SAXReader();
        File file = new File("Java_Xml\\homework\\clazs.xml");
        Document read = saxReader.read(file);
        Element rootElement = read.getRootElement();
        List<Element> elements = rootElement.elements();
        Element clazs = DocumentHelper.createDocument().addElement("clazs");
        clazs.addAttribute("id","08002");
        Element count = clazs.addElement("count");
        count.setText("22");
        Element number = clazs.addElement("number");
        number.setText("59");
        Element name = clazs.addElement("name");
        name.setText("王五");
        Element dateOfBirth = clazs.addElement("dateOfBirth");
        dateOfBirth.setText("1999-09-09");
        elements.add(0,clazs);


        OutputFormat prettyPrint = new OutputFormat().createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileWriter(file),prettyPrint);
        xmlWriter.write(read);
        xmlWriter.close();
    }
}